package com.sxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxy.controller.common.R;
import com.sxy.pojo.Category;
import com.sxy.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品分类和套餐分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增分类成功~");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getByPage(int page, int pageSize) {
        log.info("page = {},pageSize = {}", page, pageSize);
        //创建分页对象
        Page pageInfo = new Page(page, pageSize);
        //创建条件查询对象
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //创建以 Sort 字段 排序
        lqw.orderByAsc(Category::getSort);
        //执行业务层方法
        categoryService.page(pageInfo, lqw);

        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long ids) {
        log.info("删除分类，id为:{}", ids);
        //执行业务层方法
        categoryService.removeById(ids);
        return R.success("删除分类成功");
    }

    /**
     * 根据id修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类信息: {}", category);
        //执行业务层方法
        categoryService.updateById(category);

        return R.success("修改分类成功");
    }

    @GetMapping("/list")
    public R<List<Category>> getType(Category category) {
        log.info("getType...");
        //创建条件查询对象
        LambdaQueryWrapper<Category> cqw = new LambdaQueryWrapper<>();
        //添加条件
        cqw.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件,如果sort字段相同，则使用UpdateTime降序排序
        cqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        //执行业务层方法
        List<Category> list = categoryService.list(cqw);

        return R.success(list);
    }

}
